package com.lanou.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.lanou.entity.*;
import com.lanou.service.ItemDescService;
import com.lanou.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class ItemDescServiceImpl implements ItemDescService {
    @Value("${ITEM_JSON_URL}")
    private String ITEM_JSON_URL;

    @Value("${ITEM_DESC_JSON_URL}")
    private String ITEM_DESC_JSON_URL;

    @Value("${ITEM_PARAM_JSON_URL}")
    private String ITEM_PARAM_JSON_URL;

    @Value("${INDEX_CONTENT_JSON_URL}")
    private String INDEX_CONTENT_JSON_URL;

    @Value("${DESC_IMG_CID}")
    private Long DESC_IMG_CID;

    @Override
    public Item showItemById(Long id) {
        Item item = HttpClientUtils.getObject(ITEM_JSON_URL + id,Item.class);
        String[] split = item.getImage().split(",");
        item.setImages(split);
        return item;
    }

    @Override
    public TbItemDesc showItemDescById(Long id) {
        TbItemDesc tbItemDesc = HttpClientUtils.getObject(ITEM_DESC_JSON_URL + id,TbItemDesc.class);
        return tbItemDesc;
    }

    @Override
    public String showItemParamById(Long id) {
        TbItemParamItem itemParamItem = HttpClientUtils.getObject(ITEM_PARAM_JSON_URL + id,TbItemParamItem.class);
        String paramData = itemParamItem.getParamData();
        List<Map> paramList = JSONArray.parseArray(paramData, Map.class);
        String resultHtml ="<table cellpadding=\"0\" cellspacing=\"1\" width=\"100%\" border=\"0\" class=\"Ptable\">\n" +
                            "<tbody>\n";
        for (Map map : paramList) {
            resultHtml +=
                    "<tr>\n" +
                    "<th class=\"tdTitle\" colspan=\"2\">"+map.get("group")+"</th>\n" +
                    "</tr>\n";
            List<Map> params = (List<Map>) map.get("params");
            for (Map map2 : params) {
                resultHtml +=
                        "<tr>\n" +
                        "<td class=\"tdTitle\">"+ map2.get("k")+"</td>\n" +
                        "<td>"+map2.get("v")+"</td>\n" +
                        "</tr>\n";
            }
        }
        resultHtml += "</tbody>\n" +
                      "</table>";
        return resultHtml;
    }

    @Override
    public List<ContentImg> showDescImg() {
        List<TbContent> contentList = HttpClientUtils.getList(INDEX_CONTENT_JSON_URL + DESC_IMG_CID, TbContent.class);
        List<ContentImg> contentImgList = new ArrayList<>();
        for (TbContent content : contentList) {
            ContentImg contentImg = new ContentImg();
            contentImg.setSrc(content.getPic());
            contentImg.setHref(content.getUrl());
            contentImgList.add(contentImg);
        }
        return contentImgList;
    }

}
